package com.phynos.lib.dal;

import java.sql.*;

public class DBSession {

	private static final ThreadLocal<DBSession> tl = new ThreadLocal<DBSession>();
	
	private Connection conn = null;
	
	public static DBSession getCurrent() throws SQLException {
		DBSession result = tl.get();
		
		if(result == null){
			result = new DBSession();
			tl.set(result);
		}
		
		return result;
	}
	
	public static Statement getStatement() throws SQLException {
		return getCurrent().conn.createStatement();
	}
	
	public static PreparedStatement getPreparedStatement(String sql) throws SQLException {
		return getCurrent().conn.prepareStatement(sql);
	}
	
	public static PreparedStatement getPreparedStatement(String sql, int autoGeneratedKeys) throws SQLException {
		return getCurrent().conn.prepareStatement(sql, autoGeneratedKeys);
	}
	
	public static CallableStatement getCallableStatement(String sql) throws SQLException {
		return getCurrent().conn.prepareCall(sql);
	}
	
	public static void closeCurrent(boolean commit){
		DBSession current = tl.get();
		if(current == null)
			return;
		
		try{
			if(commit && current.conn != null){
				current.conn.commit();
			}
		}catch(Throwable ex){
		}finally{
			if(current.conn != null){
				try{
					current.conn.close();
				}catch(Throwable ex){}
			}
			current.conn = null;
			
			tl.remove();
		}
	}
	
	public static void commitCurrent(){
		DBSession current = tl.get();
		
		if(current == null)
			return;
		
		try{
			current.conn.commit();
		}catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}
	
	public static void rollbackCurrent(){
		DBSession current = tl.get();
		
		if(current == null)
			return;
		
		try{
			current.conn.rollback();
		}catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}
	
	private DBSession() throws SQLException {
		conn = DBFactory.newConnection();
		conn.setAutoCommit(false);
	}
}
